import {
  Button,
  Image,
  message,
  Modal,
  Space,
  TypographyText
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'

import { userApi } from '@/apis'
import mrManageApi from '@/apis/mrManageApi'
import qzyApi from '@/apis/qzyApi'
import { ProTable, ProTableProps, ProTableRef } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import router from '@/router'
import { bus, formatDate, optionsToMap } from '@/utils'

export default defineComponent({
  name: 'MrNearbyStoresList',
  setup() {
    const id = ref(0)
    const status = ref(0)
    const statusOptions = [
      { label: '全部', value: '' },
      { label: '启用', value: '1' },
      { label: '已禁用', value: '0' }
    ]
    const typesOptions = [
      { label: '自营店', value: 1 },
      { label: '授权店', value: 2 }
    ]
    const levelOptions = [
      { label: '优选店', value: 0 },
      { label: '荣耀V1优选店', value: 1 },
      { label: '荣耀V2优选店', value: 2 },
      { label: '荣耀V3优选店', value: 3 }
    ]
    const visible = ref(false)
    const statusMap = optionsToMap(statusOptions)
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref<ProTableProps>({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await mrManageApi.getStoreList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        },
        formConfig: {
          items: [
            {
              title: '门店编号',
              field: 'storeCode',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入门店编号',
                  style: {
                    width: '200px'
                  }
                }
              }
            },
            {
              title: '门店名称',
              field: 'storeName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入门店名称',
                  style: {
                    width: '200px'
                  }
                }
              }
            },
            {
              title: '门店电话',
              field: 'phone',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入门店电话',
                  style: {
                    width: '200px'
                  }
                }
              }
            },
            {
              title: '门店状态',
              field: 'validFlag',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: statusOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '门店编号',
            field: 'storeCode'
          },
          {
            title: '门店名称',
            field: 'storeName',
            width: '160px'
          },
          {
            title: '门店电话',
            field: 'phone'
          },
          {
            title: '店长二维码',
            field: 'shopQrCode',
            slots: {
              default: 'img'
            }
          },
          {
            title: '营业时间',
            field: 'createTime',
            slots: {
              default: 'time'
            },
            width: '150px'
          },
          {
            title: '门店地址',
            slots: {
              default: 'address'
            },
            width: '170px'
          },
          {
            title: '类型',
            field: 'managingType2',
            formatter: ({ cellValue }) => {
              return optionsToMap(typesOptions)[cellValue]
            }
          },
          {
            title: '标签',
            slots: {
              default: 'tag'
            },
            width: '180px'
          },
          {
            title: '门店等级',
            field: 'preferredCounter',
            width: '150px'
            // formatter: ({ cellValue }) => {
            //   return optionsToMap(levelOptions)[cellValue]
            // }
          },
          {
            title: '评分',
            field: 'counterScore',
            slots: {
              default: 'counterScore'
            }
          },
          {
            title: '状态',
            slots: {
              default: 'status'
            }
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 10
        }
      }
    })
    //刷新
    async function refresh() {
      await tableRef.value.table.commitProxy('query')
    }
    onMounted(() => {
      bus.on('refreshFormationList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })
    //新增
    function handleCreate() {
      router.push({ name: 'MrStoresEdit' })
    }
    //编辑
    function handleEdit(row) {
      router.push({ name: 'MrStoresEdit', query: { id: row.id } })
    }
    //上下架
    function handleStatus(row) {
      visible.value = true
      status.value = Number(row.validFlag)
      id.value = row.id
    }
    async function handleOk(e) {
      const commonFn = () => {
        visible.value = false
        message.success(status.value === 0 ? '启用成功' : '禁用成功')
        refresh()
      }
      const action =
        status.value === 0 ? mrManageApi.activeStore : mrManageApi.banStore
      action(id.value).then(() => {
        commonFn()
      })
    }
    return {
      visible,
      tableRef,
      tableConfig,
      status,
      refresh,
      handleCreate,
      handleStatus,
      handleOk,
      handleEdit
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            status: ({ row }) => {
              return (
                <Space>
                  {row.validFlag == '1' ? (
                    <TypographyText type="danger">启用</TypographyText>
                  ) : (
                    <TypographyText type="success">已禁用</TypographyText>
                  )}
                </Space>
              )
            },
            counterScore: ({ row }) => {
              return <div>{Number(row.counterScore / 20).toFixed(1)}</div>
            },
            img: ({ row }) => (
              <Image
                style={{
                  width: '60px',
                  height: '60px'
                }}
                src={row.shopQrCode}
              ></Image>
            ),
            time: ({ row }) => (
              <div>
                {row.workStartTime
                  ? moment(row.workStartTime, 'HH:mm').format('HH:mm')
                  : ''}
                -
                {row.workEndTime
                  ? moment(row.workEndTime, 'HH:mm').format('HH:mm')
                  : ''}
              </div>
            ),
            address: ({ row }) => (
              <div>{`${row.province}  ${row.city}  ${row.county}  ${row.address}`}</div>
            ),
            tag: ({ row }) => (
              <div>
                {[
                  row.experienceFlag,
                  row.laserMark,
                  row.parkingSpot,
                  row.peripheralProduct
                ]
                  ?.filter(k => k && k !== '0')
                  ?.join('、')}
              </div>
            ),
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleStatus(row)}
                >
                  {row.validFlag === '1' ? '禁用' : '启用'}
                </Button>
              </Space>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button
                    style={{ position: 'absolute', left: '10px', top: '5px' }}
                    type="primary"
                    onClick={this.handleCreate}
                  >
                    新增门店
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.visible}
          title={this.status === 0 ? '启用' : '禁用'}
          destroyOnClose
          onOk={this.handleOk}
          width={325}
        >
          确定{this.status === 0 ? '启用' : '禁用'}该门店吗？
        </Modal>
      </div>
    )
  }
})
